package cn.signalpha.modules.shop.listener;

import cn.signalpha.common.utils.Arith;
import cn.signalpha.core.log.exception.ServiceException;
import cn.signalpha.core.tool.jackson.JsonUtil;
import cn.signalpha.core.tool.support.Kv;
import cn.signalpha.core.tool.utils.ObjectUtil;
import cn.signalpha.core.tool.utils.StringUtil;
import cn.signalpha.modules.shop.dto.PublicityGoodsDTO;
import cn.signalpha.modules.shop.entity.enums.PublicityTypeEnum;
import cn.signalpha.modules.shop.event.SellerCartEvent;
import cn.signalpha.modules.shop.order.SellerCartEventOrder;
import cn.signalpha.modules.shop.service.PublicityGoodsService;
import cn.signalpha.modules.shop.service.PublicityService;
import cn.signalpha.modules.shop.vo.CartVO;
import cn.signalpha.modules.shop.vo.OrderConfirmVO;
import cn.signalpha.modules.shop.vo.PublicityGoodsVO;
import lombok.AllArgsConstructor;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Optional;

/**
 * 默认的购物车链进行组装时的操作
 */
@AllArgsConstructor
@Component("defaultSellerCartListener")
public class SellerCartListener {

	private final PublicityService publicityService;
	private final PublicityGoodsService publicityGoodsService;

    /**
     * 将商户下的所有商品归属到该商户的购物车当中
     */
    @EventListener(SellerCartEvent.class)
	@Order(SellerCartEventOrder.DEFAULT)
    public void defaultShopCartEvent(SellerCartEvent event) {
        CartVO cartVO = event.getCartVO();
        List<OrderConfirmVO.SellerCartItemVO> sellerCartItemList = event.getSellerCartItemList();
		cartVO.setShopCartItems(sellerCartItemList);
    }

	/**
	 * 营销活动场景 - 限时秒杀
	 */
	@EventListener(SellerCartEvent.class)
	@Order(SellerCartEventOrder.LIMIT_TIME_SEC_KILL)
	public void limitTimeDiscountShopCartEvent(SellerCartEvent event) {
		CartVO cartVO = event.getCartVO();
		String type = PublicityTypeEnum.LIMIT_TIME_SEC_KILL.getType();

		for (OrderConfirmVO.SellerCartItemVO shopCartItem : cartVO.getShopCartItems()) {
			//参与了其他优惠活动，直接跳过
			if(StringUtil.isNotBlank(shopCartItem.getDeductPublicityType())){
				continue;
			}
			PublicityGoodsVO publicityGoods = publicityGoodsService.getByGoodsIdAndType(shopCartItem.getSellerId(), shopCartItem.getGoodsId(), type);
			if(ObjectUtil.isEmpty(publicityGoods)){
				continue;
			}
			PublicityGoodsDTO.LimitTimeSecKillDTO LimitTimeSecKillDTO = JsonUtil.parse(publicityGoods.getConfig(), PublicityGoodsDTO.LimitTimeSecKillDTO.class);
			if(ObjectUtil.isEmpty(LimitTimeSecKillDTO)){
				continue;
			}
			List<PublicityGoodsDTO.LimitTimeSecKillDetailDTO> detailList = LimitTimeSecKillDTO.getDetailList();
			Optional<PublicityGoodsDTO.LimitTimeSecKillDetailDTO> configOptional = detailList.stream().filter(item -> shopCartItem.getGoodsSpec().equals(item.getSpec())).findFirst();
			if(!configOptional.isPresent()){
				continue;
			}
			PublicityGoodsDTO.LimitTimeSecKillDetailDTO config = configOptional.get();
			if(ObjectUtil.isEmpty(config.getSalesVolume()) || ObjectUtil.isEmpty(config.getStock())){
				throw new ServiceException("该商品在营销活动中未设置库存或销量");
			}
			if(config.getSalesVolume() >= config.getStock()){
				continue;
			}

			//每人限买数
			int limitNum = LimitTimeSecKillDTO.getLimitNum() == 0 ? shopCartItem.getGoodsNum() : LimitTimeSecKillDTO.getLimitNum();
			//剩余可触发数
			int surplusNum = Math.min(config.getStock() - config.getSalesVolume(), limitNum);
			//实际可触发数
			int discountedNum = Math.min(surplusNum, shopCartItem.getGoodsNum());
			//非折扣商品数
			int regularNum =  Math.max(0, shopCartItem.getGoodsNum() - discountedNum);
			//非活动价 = 商品单价 * 非折扣商品数
			double regularPrice = Arith.mul(shopCartItem.getGoodsPrice(), regularNum);
			//活动价
			double discountRate = config.getPrice();
			//活动总价 = 折扣商品数 * 活动价
			double discountPrice = Arith.mul(discountedNum, discountRate);
			double orderPrice = Arith.add(discountPrice, regularPrice);

			double deductPrice = Arith.sub(shopCartItem.getGoodsTotalPrice(), orderPrice);
			shopCartItem.setOrderPrice(orderPrice);
			shopCartItem.setDeductPublicity(deductPrice);
			shopCartItem.setDeductPublicityId(publicityGoods.getPublicityId());
			shopCartItem.setDeductPublicityType(type);
			shopCartItem.setDeductPublicityGoodsNum(discountedNum);
			shopCartItem.setDeductPublicityIsCoupon(publicityGoods.getPublicityIsCoupon());
			shopCartItem.setDeductPublicityDetail(Kv.create().set("key", "限时秒杀").set("value", publicityGoods.getPublicityTitle()).set("endTime", publicityGoods.getEndTime()));
		}
	}

	/**
	 * 营销活动场景 - N元N件
	 */
	@EventListener(SellerCartEvent.class)
	@Order(SellerCartEventOrder.N_MONEY_N_PIECE)
	public void nMoneyNPieceShopCartEvent(SellerCartEvent event) {
		CartVO cartVO = event.getCartVO();
		String type = PublicityTypeEnum.N_MONEY_N_PIECE.getType();

		for (OrderConfirmVO.SellerCartItemVO shopCartItem : cartVO.getShopCartItems()) {
			//参与了其他优惠活动，直接跳过
			if(StringUtil.isNoneBlank(shopCartItem.getDeductPublicityType())){
				continue;
			}
			PublicityGoodsVO publicityGoods = publicityGoodsService.getByGoodsIdAndType(shopCartItem.getSellerId(), shopCartItem.getGoodsId(), type);
			if(ObjectUtil.isEmpty(publicityGoods)){
				continue;
			}
			shopCartItem.setDeductPublicityType(type);
			shopCartItem.setDeductPublicityId(publicityGoods.getPublicityId());
			shopCartItem.setDeductPublicityDetail(Kv.create().set("key", "N件N件").set("value", publicityGoods.getPublicityTitle()).set("config", publicityGoods.getPublicityConfig()));
		}
	}


}
